﻿using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using DB.SchemaSync.Library.Models;

namespace DB.SchemaSync.SqlServer
{
	public partial class SqlServerDbProvider
	{
		private DataSet GetSeedData(IEnumerable<Table> tables, IDbConnection connection)
		{
			DataSet ds = new DataSet();

			var includeTables = tables.Where(t => t.MigrateData).ToArray();
			foreach (var t in includeTables)
			{
				var dataTable = FillDataTable(connection, t);
				ds.Tables.Add(dataTable);
			}

			return ds;
		}

		private DataTable FillDataTable(IDbConnection connection, Table table)
		{
			DataTable result = new DataTable(table.Schema + "." + table.Name);

			string whereClause = (!string.IsNullOrEmpty(table.MigrateDataWhere)) ?
				" WHERE " + table.MigrateDataWhere :
				string.Empty;

			using (var cmd = new SqlCommand($"SELECT * FROM [{table.Schema}].[{table.Name}]{whereClause}", connection as SqlConnection))
			{
				using (var adapter = new SqlDataAdapter(cmd))
				{
					adapter.Fill(result);
				}
			}

			return result;
		}
	}
}